const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    goodsData: "", //商品详情
    activityStatus: 0, // 1 库存不足、2 活动过期
    groupData: "", //拼团信息
    moreList: [],//更多推荐列表
    popStatus: false, //选择属性窗口显示状态
    buyType: "", //1 去拼团 ；2 单独购买
    attrData: "", //商品属性值
    selectAttr: {
      attrId: '',
      max: 9999,
      count: 1, //数量
      attr: '请选择属性规格'
    },// 选择的商品属性值
    attrIdArr: [],//选择的商品属性值的ID数组
    show: '',
    showcountDown: '00:00:00'
  },
  toShop(e){
    wx.navigateTo({
      url: '/pages/shop/shop?id=' + this.data.goodsData.shop.id
    })
  },
  // 去拼团&单独购买
  buy(e) {
    let that = this;
    that.setData({
      buyType: e.target.dataset.type
    })
    wx.showLoading({
      title: '获取商品属性',
    })
    wx.request({
      url: app.buildUrl('/active/get-active-attr'),
      header: app.buildHeader(),
      data: {
        aid: that.data.id,
        type: that.data.buyType
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 200) {
          if (res.data.data.attrlist.length == 0) {
            wx.navigateTo({
              url: '../pay/pay?id=' + res.data.data.attrone.id + '&type=' + that.data.buyType + '&num=1' + '&shopid=' + that.data.goodsData.shop.id
            })
          } else {
            for (let i = 0; i < res.data.data.attrlist.length; i++) {
              for (let j = 0; j < res.data.data.attrlist[i].val.length; j++) {
                res.data.data.attrlist[i].val[j].active = false;
                res.data.data.attrlist[i].val[j].disable = false;
              }
            }
            that.setData({
              popStatus: true,
              'selectAttr.img': res.data.data.list_img,
              'selectAttr.price': res.data.data.money,
              attrData: res.data.data,
              attrIdArr: new Array(res.data.data.attrlist.length)
            })
          }
        } else {
          app.showToast(res.data.msg)
        }
      }
    })
  },
  // 选择属性
  checked(e) {
    let that = this;
    if (e.target.dataset.disable) { return; }
    let attrId = e.target.dataset.id; //点击的属性ID
    let attrIdArr = that.data.attrIdArr;
    let idx = e.target.dataset.idx; //点击的属性IDX
    let attrData = that.data.attrData;
    let idArr = []; //存储有库存的商品ID
    let newIdArr = []; //排序、去重后的idArr
    let itemArr = [];
    attrData.attrlist[idx].val.forEach(i => {
      if (i.id == attrId) {
        if (i.active) {
          that.setData({
            'selectAttr.attrId': "",
            'selectAttr.img': that.data.attrData.list_img,
            'selectAttr.price': that.data.attrData.money,
            'selectAttr.max': 9999,
            'selectAttr.attr': '请选择属性规格'
          })
          // 取消选中状态变化
          attrIdArr.splice(attrIdArr.indexOf(attrId), 1)
          that.setData({
            attrIdArr: attrIdArr
          })
          if (attrData.attrlist.length == 2) {
            if (idx == 0) {
              attrData.attrlist[1].val.forEach(i => {
                i.disable = false;
              })
            } else {
              attrData.attrlist[0].val.forEach(i => {
                i.disable = false;
              })
            }
          }
        } else {
          // 选中状态变化
          attrData.attrlist[idx].val.forEach(i => {
            if (attrIdArr.indexOf(i.id) != -1) {
              attrIdArr.splice(attrIdArr.indexOf(i.id), 1)
            }
          })
          attrIdArr.push(attrId)
          that.setData({
            attrIdArr: attrIdArr
          })
          attrData.active_attr.forEach(i => {
            let itemId = i.attribute_value_id.split('-');
            if (itemId.indexOf(attrId) != -1) {
              itemArr.push(i);
            }
          })
          itemArr.forEach(i => {
            idArr = idArr.concat(i.attribute_value_id.split('-'))
          })
          idArr.sort((a, b) => parseInt(a) - parseInt(b));
          for (let i = 0; i < idArr.length; i++) {
            if (idArr[i] != idArr[i + 1]) {
              newIdArr.push(idArr[i])
            }
          }
          if (attrData.attrlist.length == 2) {
            if (idx == 0) {
              attrData.attrlist[1].val.forEach(i => {
                if (newIdArr.indexOf(i.id) == -1) {
                  i.disable = true;
                } else {
                  i.disable = false;
                }
              })
            } else {
              attrData.attrlist[0].val.forEach(i => {
                if (newIdArr.indexOf(i.id) == -1) {
                  i.disable = true;
                } else {
                  i.disable = false;
                }
              })
            }
          }
        }
        i.active = !i.active;
      } else {
        i.active = false;
      }
    })

    let newItemArr = itemArr;
    if (attrIdArr.length == 2) {
      attrIdArr = attrIdArr.sort((a, b) => parseInt(a) - parseInt(b));
    }
    newItemArr.forEach(i => {
      let attrId = i.attribute_value_id.split('-').filter(item => item != "0");
      if (attrIdArr.length == attrId.length) {
        attrId = attrId.sort((a, b) => parseInt(a) - parseInt(b));
        if (attrIdArr.join('') == attrId.join('')) {
          let attrStr = '已选：';
          that.data.attrData.attrlist.forEach(i => {
            i.val.forEach(i => {
              if (i.active) {
                attrStr += i.value + " ";
              }
            })
          })
          // console.log(i)
          that.setData({
            'selectAttr.attrId': i.id,
            'selectAttr.img': i.attr_img,
            'selectAttr.price': that.data.buyType == 1 ? i.collage_price : i.one_price,
            'selectAttr.max': i.inventory,
            'selectAttr.count': that.data.selectAttr.count >= i.inventory ? i.inventory : that.data.selectAttr.count,
            'selectAttr.attr': attrStr
          })
          return;
        }
      }
    })
    that.setData({
      attrIdArr: attrIdArr,
      attrData: attrData
    })
  },
  //减
  minus() {
    let that = this;
    let count = that.data.selectAttr.count;
    if (count <= 1) {
      count = 1;
    } else {
      count--;
    }
    that.setData({
      'selectAttr.count': count
    })
  },
  //加
  add() {
    let that = this;
    let count = that.data.selectAttr.count;
    if (count >= that.data.selectAttr.max) {
      app.showToast('不能超过库存数量')
      count = that.data.selectAttr.max;
    } else {
      count++;
    }
    that.setData({
      'selectAttr.count': count
    })
  },
  //确定提交
  confirm() {
    let that = this;
    if (that.data.selectAttr.attrId == "") {
      app.showToast('请选择商品属性')
      return;
    } else {
      wx.navigateTo({
        url: '../pay/pay?id=' + that.data.selectAttr.attrId + '&type=' + that.data.buyType + '&num=' + that.data.selectAttr.count + '&shopid=' + that.data.goodsData.shop.id,
      })
      that.close()
      // wx.request({
      //   url: app.buildUrl('/active/payment-info'),
      //   header: app.buildHeader(),
      //   data: {
      //     addr_id: 0,
      //     attr_id: that.data.selectAttr.attrId,
      //     num: that.data.selectAttr.count,
      //     type: that.data.buyType
      //   },
      //   success(res) {
      //     if (res.data.code == 200) {
            
      //     } else {
      //       app.showToast(res.data.msg)
      //     }
      //   }
      // })
    }
  },
  // 关闭选择属性窗口
  close() {
    this.setData({
      popStatus: false,
      attrIdArr: [],
      'selectAttr.attrId': '',
      'selectAttr.count': 1,
      'selectAttr.max': 9999
    })
  },
  //收藏切换
  star() {
    let that = this;
    if (that.data.goodsData.collect == 0) { //0 没有收藏
      wx.showLoading({
        title: '正在请求操作',
      })
      wx.request({
        url: app.buildUrl('/user/add-collection'),
        header: app.buildHeader(),
        data: {
          id: that.data.id,
          type:0
        },
        success(res) {
          wx.hideLoading()
          app.showToast(res.data.msg)
          if (res.data.code == 200) {
            that.setData({
              'goodsData.collect': 1
            })
          } else {
            app.showToast(res.data.msg)
          }
        }
      })
    } else { //1 已收藏
      wx.showModal({
        title: '提示',
        content: '确定要取消收藏？',
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '正在请求操作',
            })
            wx.request({
              url: app.buildUrl('/user/del-collection'),
              header: app.buildHeader(),
              data: {
                id: that.data.id
              },
              success(res) {
                wx.hideLoading()
                app.showToast(res.data.msg)
                if (res.data.code == 200) {
                  that.setData({
                    'goodsData.collect': 0
                  })
                } else {
                  app.showToast(res.data.msg)
                }
              }
            })
          }
        }
      })
    }
  },
  //授权
  onGotUserInfo(e) {
    let that = this;
    if (e.detail.userInfo) {
      that.setData({
        show: false,
      });
      wx.setStorageSync('status', 200);
      wx.request({
        url: app.buildUrl('/user/save-user-info'),
        header: app.buildHeader(),
        method: 'POST',
        data: {
          url: e.detail.userInfo.avatarUrl,
          nickname: e.detail.userInfo.nickName
        },
        success: res => {
          // wx.redirectTo({
          //   url: '../index/index'
          // })
          if (res.data.code == 200) {
            that.loadUrl();
          }
        }
      })
    }
  },
  //获取数据
  loadUrl() {
    let that = this;
    let id = that.data.id;
    wx.showLoading({
      title: '获取拼团信息',
    })
    // 获取拼团详细信息
    wx.request({
      url: app.buildUrl('/active/get-activity-info'),
      header: app.buildHeader(),
      data: {
        aid: id
      },
      success(res) {
        wx.hideLoading()
        let data = res.data.data;
        if (res.data.code == 200) {
          if (data.active_count == "0") {
            that.setData({
              activityStatus: 1
            })
          }
        } else if (res.data.code == -1) {
          that.setData({
            activityStatus: 2
          })
        }
        that.setData({
          goodsData: data
        })
      }
    })

    //获取参团信息
    wx.request({
      url: app.buildUrl('/active/get-group-list'),
      header: app.buildHeader(),
      data: {
        aid: id
      },
      success(res) {
        if (res.data.code == 200) {
          let data = res.data.data;
          if (data.group_all != "") {
            data.group_all.forEach(i => {
              app.transformTime(parseInt(i.group.complete_time) * 1000, options => {
                i.group.complete_time = `${options.Y}-${options.M}-${options.D} ${options.h}:${options.m}:${options.s}`
              })
            })
          }
          if (data.group_one != "") {
            app.countDown({
              date: parseInt(data.group_one.expire_time) * 1000,
              fun: options => {
                that.setData({
                  showcountDown: options.d >= 1 ? `${options.d}天 ${options.h}:${options.m}:${options.s}` : `${options.h}:${options.m}:${options.s}`
                })
              },
              endFun: () => {
                that.setData({
                  showcountDown: "00:00:00"
                })
              }
            })
          }
          that.setData({
            groupData: data
          })
        } else {
          app.showToast(res.data.msg)
        }
      }
    })

    //获取更多推荐
    wx.request({
      url: app.buildUrl('/active/get-more'),
      header: app.buildHeader(),
      data: {
        id: that.data.id
      },
      success(res) {
        if (res.data.code == 200) {
          that.setData({
            moreList: res.data.data
          })
        } else {
          app.showToast(res.data.msg)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log(options)
    console.log(decodeURIComponent(options))
    let id = options.id ? options.id : options.scene ? decodeURIComponent(options.scene) : '1';
    
    that.setData({
      id: id
    })
    app.getUserInfoFirst().then(function (res) {
      if (res.status == 200) {
        if (wx.getStorageSync("status") != 200) {
          that.setData({ show: true })
        } else if (wx.getStorageSync("status") == 200) {
          that.setData({ show: false })
          that.loadUrl();
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    if (res.from === 'button') {
      return {
        title: that.data.goodsData.active_name,
        path: '/pages/detail/detail?id=' + that.data.goodsData.id,
        imageUrl: that.data.goodsData.goods_img
      }
    }
  }
})